/**
 * 超级管理员服务实现类
 *
 * 开发人员：徐少洋
 * 开发时间：2025-11-21
 * 模块职责：实现超级管理员的认证、授权和管理功能
 */
package com.pbl.service.impl;

import com.pbl.common.exception.BizException;
import com.pbl.entity.SuperAdmin;
import com.pbl.entity.SuperAdminLog;
import com.pbl.repository.SuperAdminLogRepository;
import com.pbl.repository.SuperAdminRepository;
import com.pbl.security.JwtUtil;
import com.pbl.service.SuperAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SuperAdminServiceImpl implements SuperAdminService {
    
    private final SuperAdminRepository superAdminRepository;
    private final SuperAdminLogRepository superAdminLogRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;
    
    public SuperAdminServiceImpl(SuperAdminRepository superAdminRepository,
                                SuperAdminLogRepository superAdminLogRepository,
                                PasswordEncoder passwordEncoder,
                                JwtUtil jwtUtil) {
        this.superAdminRepository = superAdminRepository;
        this.superAdminLogRepository = superAdminLogRepository;
        this.passwordEncoder = passwordEncoder;
        this.jwtUtil = jwtUtil;
    }
    
    @Override
    @Transactional
    public Map<String, Object> login(String username, String password) {
        SuperAdmin superAdmin = superAdminRepository.findByUsername(username)
            .orElseThrow(() -> new BizException(401, "用户名或密码错误"));
        
        if (superAdmin.getStatus() != 1) {
            throw new BizException(403, "账号已被禁用");
        }
        
        if (!passwordEncoder.matches(password, superAdmin.getPasswordHash())) {
            throw new BizException(401, "用户名或密码错误");
        }
        
        // 更新最后登录时间
        superAdmin.setLastLoginAt(LocalDateTime.now());
        superAdminRepository.save(superAdmin);
        
        // 生成JWT Token（超级管理员标识）
        Map<String, Object> claims = new HashMap<>();
        claims.put("superAdminId", superAdmin.getId());
        claims.put("isSuperAdmin", true);
        String token = jwtUtil.generateToken(superAdmin.getUsername(), claims);
        
        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("superAdmin", superAdmin);
        result.put("isSuperAdmin", true);
        
        log.info("超级管理员登录成功: {}", username);
        return result;
    }
    
    @Override
    @Transactional
    public SuperAdmin create(SuperAdmin superAdmin, String password) {
        if (superAdminRepository.existsByUsername(superAdmin.getUsername())) {
            throw new BizException(400, "用户名已存在");
        }
        
        if (superAdminRepository.existsByEmail(superAdmin.getEmail())) {
            throw new BizException(400, "邮箱已存在");
        }
        
        superAdmin.setPasswordHash(passwordEncoder.encode(password));
        superAdmin.setStatus(1);
        
        return superAdminRepository.save(superAdmin);
    }
    
    @Override
    @Transactional
    public SuperAdmin update(Long id, SuperAdmin superAdmin) {
        SuperAdmin existing = get(id);
        
        if (superAdmin.getEmail() != null && !superAdmin.getEmail().equals(existing.getEmail())) {
            if (superAdminRepository.existsByEmail(superAdmin.getEmail())) {
                throw new BizException(400, "邮箱已存在");
            }
            existing.setEmail(superAdmin.getEmail());
        }
        
        if (superAdmin.getPhone() != null) {
            existing.setPhone(superAdmin.getPhone());
        }
        
        if (superAdmin.getRealName() != null) {
            existing.setRealName(superAdmin.getRealName());
        }
        
        if (superAdmin.getStatus() != null) {
            existing.setStatus(superAdmin.getStatus());
        }
        
        return superAdminRepository.save(existing);
    }
    
    @Override
    public SuperAdmin get(Long id) {
        return superAdminRepository.findById(id)
            .orElseThrow(() -> new BizException(404, "超级管理员不存在"));
    }
    
    @Override
    public List<SuperAdmin> list() {
        return superAdminRepository.findAll();
    }
    
    @Override
    @Transactional
    public void logAction(Long superAdminId, String action, String targetType, Long targetId,
                         String detail, String ipAddress, String userAgent) {
        SuperAdmin superAdmin = get(superAdminId);
        
        SuperAdminLog log = SuperAdminLog.builder()
            .superAdmin(superAdmin)
            .action(action)
            .targetType(targetType)
            .targetId(targetId)
            .detail(detail)
            .ipAddress(ipAddress)
            .userAgent(userAgent)
            .build();
        
        superAdminLogRepository.save(log);
    }
    
    @Override
    public Page<SuperAdminLog> getLogs(Long superAdminId, int page, int size) {
        return superAdminLogRepository.findBySuperAdmin_IdOrderByCreatedAtDesc(
            superAdminId, PageRequest.of(page, size));
    }
    
    @Override
    public List<SuperAdminLog> getTargetLogs(String targetType, Long targetId) {
        return superAdminLogRepository.findByTargetTypeAndTargetIdOrderByCreatedAtDesc(
            targetType, targetId);
    }
}

